util.PrecacheSound( "coast.siren_citizen" )
util.PrecacheSound( "explode_9" )

	AddCSLuaFile("shared.lua")
	AddCSLuaFile("cl_init.lua")
	
	include('shared.lua')
	function ENT:Initialize()
		-- don't forget collision group none
		if (not (self.Mass and self.TonGrade)) then
			self.Entity:Remove()
		end
		self.Entity:SetModel(self.Entity.Model)
		self.Entity:PhysicsInit (SOLID_VPHYSICS)
		
		self.Entity:Activate()
		
		self.SpecialHealth = true
		self.SpecialDamage = true
		self.Exploding = false
		self.NextExplode = 0
		self.NextConstraintCheck = 0
		self.NextSpark = 0
		self.HasFriends = false
		self.IsDead = false
		
		local phys = self.Entity:GetPhysicsObject()
		if(phys:IsValid()) then
			phys:SetMass(self.Mass)
			phys:Wake()
		end
		
		self:NextThink( CurTime() + math.random() )
	end
	
	function ENT:CheckConstraints()
		if(self.HasFriends) then return end
		self.TotalTonnage = self:GetPhysicsObject():GetMass()
		self.TotalTonGrade = self.TonGrade
		local chk = false
		local allents = constraint.GetAllConstrainedEntities( self.Entity )
		for _, ent in pairs(allents) do
			if (ent and ent:IsValid() and not ent:IsPlayer() and not (ent == self)) then
				local phys = ent:GetPhysicsObject()
				if(phys:IsValid()) then
					self.TotalTonnage = self.TotalTonnage + phys:GetMass()
				end
				if (ent:GetClass() == "sitp_core") then
					self.TotalTonGrade = self.TotalTonGrade + ent.TonGrade
					ent.HasFriends = true
				end
			end
		end
		if((self.TotalTonnage / 1000) < self.TotalTonGrade) then
			chk = true
		end
		for _, ent in pairs(allents) do
			if(ent and ent:IsValid() and not ent:IsPlayer()) then
				ent.sitp_core = chk
			end
		end
	end
	
	function ENT:CoreExplode()
		local Pos = self.Entity:GetPos()
		local r, g, b, a = self:GetColor()
		--local shc = (r + g * 1000 + b * 1000000) / 1000000
		local effectdata = EffectData()
			effectdata:SetMagnitude( 1 )
			effectdata:SetAngle(Angle(r, g, b))
			effectdata:SetOrigin( Pos )
			effectdata:SetScale( self.TonGrade / 200 )
		util.Effect( "warpcore_breach", effectdata )
		local tAllPlayers = player.GetAll()
		for _, pPlayer in pairs( tAllPlayers ) do
			pPlayer.Entity:EmitSound( "explode_9" )
		end
		self:EmitSound( "explode_9" )
		
		local inf = self.Entity
		
		if( self.Inflictor ) then inf = self.Inflictor end
		ACF_HE( Pos , Vector(0,0,1) , self.Mass / 4 , self.Mass * 3/4 , inf , self.Entity )
		
		local shake = ents.Create("env_shake")
		shake:SetKeyValue("amplitude", "16")
		shake:SetKeyValue("duration", "6")
		shake:SetKeyValue("radius", 1 * self.TonGrade) 
		shake:SetKeyValue("spawnflags", 5) 
		shake:SetKeyValue("frequency", "240")
		shake:SetPos(Pos)
		shake:Spawn()
		shake:Fire("StartShake","","0.6")
		shake:Fire("kill","","8")
		
		--timer.Simple(0.2, function() self:Remove() end)
	end
	
	function ENT:ExplodeCheck()
		self.TotalTonnage = 0
		self.TotalTonGrade = 0
		
		local chk = false
		local allents = constraint.GetAllConstrainedEntities( self.Entity )
		for _, ent in pairs(allents) do
			if (ent and ent:IsValid() and not ent:IsPlayer()) then
				local phys = ent:GetPhysicsObject()
				if(phys:IsValid()) then
					self.TotalTonnage = self.TotalTonnage + phys:GetMass()
				end
				if (ent:GetClass() == "sitp_core") then
					self.TotalTonGrade = self.TotalTonGrade + ent.TonGrade
					ent.HasFriends = false -- Need to make sure they realize that I just exploded.
				end
			end
		end
		if((self.TotalTonnage / 1000) < self.TotalTonGrade) then
			chk = true
		end
		self:CoreExplode()
		if(chk == true) then
			for _, ent in pairs(allents) do
				if(ent and ent:IsValid() and not ent:IsPlayer()) then
					local hv = (ent:GetPos() - self:GetPos())
					local energy = self.TotalTonGrade
					if (ent:GetClass() == "sitp_core") then
						ent.Exploding = true
						ent.NextExplode = CurTime() + 2 + math.random(0, 4)
						ent:EmitSound( "coast.siren_citizen", true, true)
					else
						ACF_HEKill( ent , hv , energy )
					end
				end
			end
		end
	end
	
	function ENT:ACF_Activate( Recalc )
		local Mass = self.Entity:GetPhysicsObject():GetMass() / 4
		local Size = self.Entity.OBBMaxs(self) - self.Entity.OBBMins(self)
		local Aera = ((Size.x*Size.y)+(Size.x * Size.z)+(Size.y * Size.z)) * 6.45
		local Volume = Size.x * Size.y * Size.z * 16.38
		local Armour = Mass * 1000 / Aera / 0.78
		local Health = Volume/ACF.Threshold
		local Percent = 1
		
		if Recalc then
			Percent = self.ACF.Health / self.ACF.MaxHealth
		end
		self.ACF = {}
		self.ACF.Health = Health * Percent
		self.ACF.MaxHealth = Health
		self.ACF.Armour = Armour * (0.5 + Percent / 2)
		self.ACF.MaxArmour = Armour
		self.ACF.Type = nil
		self.ACF.Mass = self.Mass
		self.ACF.Density = (self:GetPhysicsObject():GetMass() * 1000) / Volume
		self.ACF.Type = "Prop"
	end
	
	function ENT:ACF_OnDamage( Entity, Energy, FrAera, Angle, Inflictor )
		local HitRes = {}
			HitRes.Damage = 0
			HitRes.Overkill = 0
			HitRes.Loss = 1
			HitRes.Kill = false
			HitRes.Ricochet = true
		if( self.Owner.sitp_team == self.sitp_spacetype ) or (self.sitp_spacetype == "all") then
			return HitRes
		end
		
		if( !self.Exploding ) then
			if( Inflictor and Inflictor:IsPlayer()) then
				self.Inflictor = Inflictor
			end
			self.Exploding = true
			self.NextExplode = CurTime() + 15
			self:EmitSound( "coast.siren_citizen", true, true)
		end
		
		return HitRes
	end
	
	function ENT:Think()
		if( (self.NextExplode < CurTime()) and ( self.Exploding ) and !self.IsDead) then
			self:StopSound( "coast.siren_citizen" )
			self:ExplodeCheck()
			
			self.IsDead = true
			self.NextExplode = CurTime() + 0.2
		end
		
		if((self.NextExplode < CurTime()) and self.IsDead) then
			self:Remove()
			return
		end
		
		if( (self.NextConstraintCheck < CurTime()) ) then
			self:CheckConstraints()
			
			self.NextConstraintCheck = CurTime() + 10
		end
		if( (self.NextSpark < CurTime()) and (self.Exploding) ) then
			local num = math.random(1, 3)
			if num > 1 then
				num = num + 1
			end
			self:EmitSound( "ambient/levels/labs/electric_explosion" ..tostring( num ).. ".wav", true, true )
			self.NextSpark = CurTime() + (1 + math.random(0, 2)) * 0.5
			
			local ang = self:GetAngles()
			local boxmax = self:OBBMaxs()
			local boxmin = self:OBBMins()
			local pos = (self:GetPos() + (ang:Up() * boxmax.x))
			local r, g, b, a = self:GetColor() 
			for i = 1, 4 do
				local disp = ang:Forward() * math.random(boxmin.x, boxmax.x) + ang:Right() * math.random(boxmin.y, boxmax.y)
				local mag = self.TonGrade / 20 * math.random(1, 4)
				zapme((pos + disp), mag, r, g, b)
			end
		end
		
		self:NextThink( CurTime() + 0.1 )
		--print("sitp_core was just thinking. next constraint check in " .. tostring(self.NextConstraintCheck - CurTime()))
	end
	
	function ENT:OnRemove()
		self:StopSound( "coast.siren_citizen" )
	end
	
	function zapme(pos, magnitude, r, g, b)
		zap = ents.Create("point_tesla")
		zap:SetKeyValue("targetname", "teslab")
		zap:SetKeyValue("m_SoundName", "DoSpark")
		zap:SetKeyValue("texture", "sprites/laser.spr")
		zap:SetKeyValue("m_Color", tostring(math.Clamp(r, 0, 255)) .. " " .. tostring(math.Clamp(g, 0, 255)) .. " " .. tostring(math.Clamp(b, 0, 255)))
		zap:SetKeyValue("m_flRadius", tostring(magnitude*10))
		zap:SetKeyValue("beamcount_min", tostring(math.ceil(magnitude)+0))
		zap:SetKeyValue("beamcount_max", tostring(math.ceil(magnitude)+4))
		zap:SetKeyValue("thick_min", tostring(magnitude))
		zap:SetKeyValue("thick_max", tostring(magnitude*8))
		zap:SetKeyValue("lifetime_min", "0.1")
		zap:SetKeyValue("lifetime_max", "0.2")
		zap:SetKeyValue("interval_min", "0.05")
		zap:SetKeyValue("interval_max", "0.08")
		zap:SetPos(pos)
		zap:Spawn()
		zap:Fire("DoSpark", "", 0)
		zap:Fire("kill", "", 1)
	end